<template>
    <el-card style="height: 76px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名:">
                <el-input placeholder="请输入要搜索的用户名" v-model="keywords"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" :disabled="keywords ? false : true" @click="search">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin:10px 0">
        <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
        <el-button type="primary" size="default" :disabled="selectArr.length ? false : true"
            @click="deleteSelectUser">批量删除</el-button>
        <!-- 表格展示用户的信息 -->
        <el-table style="margin:10px 0" border :data="userArr" @selection-change="selectChange">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column type="index" align="center" label="#" show-overflow-tooltip></el-table-column>
            <el-table-column label="ID" align="center" prop="id" width="80px" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户职位" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center" show-overflow-tooltip>
                <template #="{ row, $index }">
                    <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" @click="editRole(row)" icon="Edit">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.username}吗?`" @confirm="deleteUser(row)" width="200px">
                        <template #reference>
                            <el-button type="primary" size="small" @click="removeRole" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 8, 10]"
            :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
            @size-change="handleSizeChange" @current-change="getHasUser" />
    </el-card>
    <!-- 抽屉结构 完成添加新的用户账号以及修改已有的用户信息 -->
    <el-drawer v-model="drawer">
        <!-- 头部的标题:将来的文字应该是动态的 -->
        <template #header>
            <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
        </template>
        <!-- 身体部分 -->
        <template #default>
            <el-form :model="userParams" :rules="rules" ref="formRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请输入用户名" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请输入用户昵称" v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                    <el-input placeholder="请输入用户的密码" show-password v-model="userParams.password" type="password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="sendUser">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 抽屉结构 完成分配角色信息 -->
    <el-drawer v-model="drawer1">
        <!-- 头部的标题:将来的文字应该是动态的 -->
        <template #header>
            <h4>分配角色(职位)</h4>
        </template>
        <!-- 身体部分 -->
        <template #default>
            <el-form>
                <el-form-item label="用户姓名">
                    <el-input v-model="userParams.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox @change="handleCheckAllChange" v-model="checkStatus"
                        :indeterminate="indeterminate">全选</el-checkbox>
                    <!-- 显示职位的的复选框 通过遍历循环打印职位-->
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">{{ role.roleName
                        }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer1 = false">取消</el-button>
                <el-button type="primary" @click="sendRole">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang='ts'>
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入请求全部用户数据的方法
import { reqSelectUser, reqRemoveUser, reqSetUserRole, reqUserInfo, reqAddOrUpdateUser, reqGetRole } from '@/api/acl/user';
//引入请求全部用户数据的返回值类型
import type { SetRoleData, UserResponseData, Records, User, AllRoleResponseData, AllRole } from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';
//引入用户仓库
import useLayoutSettingStore from '@/store/modules/setting';

//实例化仓库
let settingStore = useLayoutSettingStore()
//定义分页器当前页码
let pageNo = ref<number>(0)
//定义分页器单页数据数量
let pageSize = ref<number>(3)
//定义分页器总页面的数量
let total = ref<number>(20)
//定义存储获取到的用户的信息的数组
let userArr = ref<Records>([])
// 定义控制添加和更新角色信息抽屉的状态的变量
let drawer = ref<boolean>(false)
// 定义控制分配角色抽屉的状态的变量
let drawer1 = ref<boolean>(false)
// 收集用户信息的响应式数据对象
let userParams = reactive<User>({
    username: '',
    password: '',
    name: '',
})
// 定义获取form组件实例的变量
let formRef = ref()
// 收集用户输入的搜索关键字
let keywords = ref<string>('')
// 定义数据条数改变的回调
const handleSizeChange = () => {
    getHasUser()
}

//修改信息按钮的回调
/**
 * 
 * @param row 已有的用户信息
 */
const editRole = (row: User) => {
    // 存储收集到的用户信息
    Object.assign(userParams, row)
    // 清理表单验证的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
    })
    //显示抽屉
    drawer.value = true;
}
//删除角色按钮的回调
const removeRole = () => {
}
// 添加用户按钮的回调
const addUser = () => {
    // 清理表单验证的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
        formRef.value.clearValidate('password')
    })
    // 清空暂存的用户数据
    Object.assign(userParams, {
        username: '',
        password: '',
        name: '',
        id: 0,
    })
    //显示抽屉
    drawer.value = true;
}
//确认添加用户的回调
const sendUser = async () => {
    // 点击按钮时需要保证表单全部验证通过
    await formRef.value.validate();
    //点击保存按钮,确认添加用户|更新已有的用户信息
    let result = await reqAddOrUpdateUser(userParams);
    if (result.code == 200) {
        // 关闭抽屉
        drawer.value = false;
        // 提示成功
        ElMessage({
            type: 'success',
            message: userParams.id ? '更新成功' : '添加成功',
        })
        window.location.reload();
    } else {
        // 关闭抽屉
        drawer.value = false;
        // 提示失败
        ElMessage({
            type: "error",
            message: userParams.id ? '添加失败' : '添加失败',
        })
    }
}
// 校验用户名的回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
    // 用户名|昵称,长度至少5位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户名至少五位'));
    }
}
// 校验用户昵称的回调函数
const validatorName = (rule: any, value: any, callBack: any) => {
    // 用户名|昵称,长度至少5位
    console.log(123)
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('昵称至少5 位'));
    }
}
// 校验用户密码的回调函数
const validatorPassword = (rule: any, value: any, callBack: any) => {
    // 用户名|昵称,长度至少5位
    console.log(123)
    if (value.trim().length >= 6) {
        callBack();
    } else {
        callBack(new Error('密码至少6位'));
    }
}
// 表单校验的规则对象
const rules = {
    // 用户名 
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    // 用户昵称 
    name: [{ required: true, trigger: 'blur', validator: validatorName }],
    // 用户密码
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
//获取数据的方法
const getHasUser = async (paper = 1) => {
    //收集传递过来的数据
    pageNo.value = paper;
    let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keywords.value)
    if (result.code == 200) {
        userArr.value = result.data.records;
        total.value = result.data.total;
    }
}
//组件挂载时获取数据
onMounted(() => {
    getHasUser()
})
// 分配角色的按钮的回调
const setRole = async (row: User) => {
    // 存储已有的用户信息
    Object.assign(userParams, row);
    let result: AllRoleResponseData = await reqGetRole((userParams.id as number));
    if (result.code == 200) {
        // 存储全部的职位
        allRole.value = result.data.allRolesList;
        // 存储当前已经拥有的职位
        userRole.value = result.data.assignRoles;
        console.log(userRole.value, allRole.value)
        // 显示抽屉
        drawer1.value = true;
    }
}

// 职位列表数据
let allRole = ref<AllRole>([]);
let userRole = ref<AllRole>([]);
// 全选复选框收集数据:是否全选
let checkStatus = ref<boolean>(false);
// 用于存储批量删除用户的数据的数组
let selectArr = ref<User[]>([])
// 设置不确定状态
const indeterminate = ref<boolean>(true)

//顶部的全选框的change事件
const handleCheckAllChange = (val: boolean) => {
    //val:true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : [];
    //不确定的样式(确定样式)
    indeterminate.value = false
}
//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    //顶部复选框的勾选数据
    //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    checkStatus.value = value.length === allRole.value.length;
    //不确定的样式
    indeterminate.value = value.length !== allRole.value.length
}
// 分配职位的确定按钮的回调
const sendRole = async () => {
    // 收集数据
    let data: SetRoleData = {
        userId: (userParams.id as number),
        roleIdList: userRole.value.map(item => {
            return (item.id as number)
        })
    }
    let result = await reqSetUserRole(data)
    console.log(result)
    if (result.code == 200) {
        //提示信息
        ElMessage({ type: 'success', message: '分配职位成功' })
        // 关闭抽屉
        drawer1.value = false;
        // 刷新用户信息
        getHasUser(pageNo.value);
    } else {
        ElMessage({
            type: "error",
            message: '分配职位失败'
        })
    }
}
// 删除某一用户
const deleteUser = async (row: User) => {
    let result: any = await reqRemoveUser((row.id as number))
    if (result.code == 200) {
        ElMessage({ type: 'success', message: "删除成功" })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({ type: 'error', message: "删除失败" })
    }
}
// 复选框勾选时触发的事件
const selectChange = (value: any) => {
    selectArr.value = value
}
// 批量删除按钮的回调函数
const deleteSelectUser = async () => {
    // 整理批量删除的参数
    let idList: any = selectArr.value.map(item => {
        return item.id
    })
    // 批量删除的请求
    let result: any = await reqSelectUser(idList)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: "删除成功" })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        console.log(result)
        ElMessage({ type: 'error', message: "删除失败" })
    }
}
// 搜索按钮的回调
const search = () => {
    // 根据关键字获取用户信息
    getHasUser();
    keywords.value = '';
}
// 重置数据
const reset = () => {
    settingStore.refresh = !settingStore.refresh;
}
</script>
<style lang='scss' scoped>
.form {
    display: flex;
    justify-content: space-between;
}
</style>